const gulp = require('gulp')
const clean = require('gulp-clean')
const childProcess = require('child_process')

const cssPath = ['src/**/*.less', 'src/**/*.css']


gulp.task('clean', () => {
  return gulp.src(['lib'], {
      read: false,
      allowEmpty: true
    })
    .pipe(clean())
})



gulp.task('css', () => {
  return gulp.src(cssPath, {
      allowEmpty: true
    })
    .pipe(gulp.dest('lib'))
})


gulp.task('watch', () => {
  gulp.watch(cssPath, gulp.series('css'))
})

const cmd = (cmdStr) => {
  return new Promise((resolve) => {
    childProcess.exec(cmdStr, {
      maxBuffer: 1024 * 2000
    }, function (err, stdout, stderr) {
      if (err) {
        console.log(err);
      } else if (stderr.lenght > 0) {
        console.error(stderr.join('\n'))
      } else {
        console.log(stdout);
      }

      resolve()
    });
  })
}

gulp.task('yalc:push', cb => {
  cmd('yalc push').then(() => cb())
})

gulp.task('watch:dev', () => {
  gulp.watch(cssPath, gulp.series('css', 'yalc:push'))
})

gulp.task('default', gulp.series('clean', gulp.parallel('watch', 'css')))

gulp.task('build', gulp.series('clean', gulp.parallel('css')))